# -*- coding: utf-8 -*-
"""
命令行界面模块
提供用户交互功能
"""

import os
import sys
from typing import Dict, List, Any, Optional
from .menu_system import MenuSystem
from .ui_components import UIComponents


class CLIInterface:
    """命令行界面类"""
    
    def __init__(self, plugin_manager, config_manager):
        """初始化命令行界面"""
        self.plugin_manager = plugin_manager
        self.config_manager = config_manager
        self.menu_system = MenuSystem(plugin_manager, config_manager)
        self.ui = UIComponents()
        self.running = True
        
    def start(self):
        """启动命令行界面"""
        try:
            # 显示欢迎信息
            self.show_welcome()
            
            # 启动菜单系统
            self.menu_system.start()
            
        except KeyboardInterrupt:
            self.safe_exit()
        except Exception as e:
            self.ui.show_error_with_guide(
                f"程序运行出错: {str(e)}",
                "请重新启动程序或联系开发者"
            )
            
    def show_welcome(self):
        """显示欢迎信息"""
        self.ui.clear_screen()
        
        # ASCII艺术字欢迎标题
        welcome_art = """
 ╔════════════════════════════════════════════════════════╗
 ║                                                        ║
 ║    ████████╗ ██████╗  ██████╗ ██╗     ██████╗  ██████╗ ║
 ║    ╚══██╔══╝██╔═══██╗██╔═══██╗██║     ██╔══██╗██╔═══██╗║
 ║       ██║   ██║   ██║██║   ██║██║     ██████╔╝██║   ██║║
 ║       ██║   ██║   ██║██║   ██║██║     ██╔══██╗██║   ██║║
 ║       ██║   ╚██████╔╝╚██████╔╝███████╗██████╔╝╚██████╔╝║
 ║       ╚═╝    ╚═════╝  ╚═════╝ ╚══════╝╚═════╝  ╚═════╝ ║
 ║                                                        ║
 ║                   多功能工具箱 v2.0                    ║
 ║                                                        ║
 ╚════════════════════════════════════════════════════════╝
        """
        print(welcome_art)
        
        # 显示加载信息
        print("\n🔧 正在初始化工具箱...")
        self.ui.show_loading("加载插件", 0.5)
        
        # 显示已加载的插件数量
        plugins = self.plugin_manager.get_loaded_plugins()
        print(f"✅ 成功加载 {len(plugins)} 个工具模块")
        
        # 显示操作提示
        print("\n📋 操作提示:")
        print("   • 使用数字键选择菜单项")
        print("   • 输入 'B' 返回上级菜单")
        print("   • 按 Ctrl+C 随时安全退出")
        
        self.ui.wait_for_enter("按回车键进入主菜单")
        
    def safe_exit(self):
        """安全退出"""
        self.ui.clear_screen()
        print("\n👋 感谢使用多功能工具箱！")
        print("   如有问题或建议，欢迎反馈！")
        self.running = False
        
    # 保留原有的方法以兼容旧代码
    def process_command(self, command: str):
        """处理用户命令（兼容性方法）"""
        parts = command.split()
        if not parts:
            return
            
        cmd = parts[0].lower()
        args = parts[1:]
        
        if cmd in ['exit', 'quit']:
            self.running = False
        elif cmd == 'help':
            self.show_help()
        elif cmd == 'list':
            self.list_plugins()
        elif cmd == 'config':
            self.show_config_menu()
        else:
            # 尝试执行插件
            if self.plugin_manager.execute_plugin(cmd, args):
                return
            else:
                self.ui.show_error_with_guide(
                    f"未知命令: {cmd}",
                    "输入 'help' 查看可用命令"
                )
                
    def show_help(self):
        """显示帮助信息"""
        self.ui.clear_screen()
        print("📚 帮助信息\n")
        
        help_content = [
            "基本命令:",
            "  help     - 显示此帮助信息",
            "  list     - 显示已加载的插件",
            "  config   - 配置管理",
            "  exit     - 退出程序",
            "",
            "插件命令:",
        ]
        
        plugins = self.plugin_manager.get_loaded_plugins()
        if plugins:
            for name, plugin in plugins.items():
                help_content.append(f"  {name:<10} - {plugin.description}")
        else:
            help_content.append("  (没有已加载的插件)")
            
        for line in help_content:
            print(line)
            
        self.ui.wait_for_enter()
        
    def list_plugins(self):
        """列出已加载的插件"""
        self.ui.clear_screen()
        print("🔌 已加载的插件\n")
        
        plugins = self.plugin_manager.get_loaded_plugins()
        if not plugins:
            print("没有已加载的插件")
            self.ui.wait_for_enter()
            return
            
        plugin_content = []
        for i, (name, plugin) in enumerate(plugins.items(), 1):
            status = "✅ 启用" if plugin.enabled else "❌ 禁用"
            plugin_content.append(f"[{i}] {plugin.description}")
            plugin_content.append(f"    名称: {name} | 版本: {plugin.version} | 状态: {status}")
            plugin_content.append("")
            
        for line in plugin_content:
            print(line)
            
        self.ui.wait_for_enter()
        
    def show_config_menu(self):
        """显示配置菜单"""
        while self.running:
            self.ui.clear_screen()
            print("⚙️  配置管理\n")
            
            menu_content = [
                "[1] 查看当前配置",
                "[2] 修改配置",
                "[3] 重置配置",
                "",
                "0. 返回主菜单"
            ]
            
            menu_lines = self.ui.draw_box(menu_content, 30)
            for line in menu_lines:
                print(line)
                
            choice = self.ui.get_user_choice("请选择操作", allow_back=False)
            
            if choice == "0":
                break
            elif choice == "1":
                self.show_current_config()
            elif choice == "2":
                self.modify_config()
            elif choice == "3":
                self.reset_config()
            else:
                self.ui.show_error_with_guide(
                    "无效的选择",
                    "请输入对应的数字编号"
                )
                self.ui.wait_for_enter()
                
    def show_current_config(self):
        """显示当前配置"""
        self.ui.clear_screen()
        print("📋 当前配置\n")
        
        config = self.config_manager.get_all_config()
        for key, value in config.items():
            print(f"  {key}: {value}")
            
        self.ui.wait_for_enter()
        
    def modify_config(self):
        """修改配置"""
        self.ui.clear_screen()
        print("✏️  修改配置\n")
        print("功能开发中...")
        self.ui.wait_for_enter()
        
    def reset_config(self):
        """重置配置"""
        self.ui.clear_screen()
        print("🔄 重置配置\n")
        
        confirm = input("确定要重置所有配置吗？(y/N): ").strip().lower()
        if confirm == 'y':
            self.config_manager.reset_config()
            print("✅ 配置已重置")
        else:
            print("❌ 操作已取消")
            
        self.ui.wait_for_enter()
        cmd = parts[0].lower()
        args = parts[1:] if len(parts) > 1 else []
        
        # 内置命令
        if cmd in ['help', 'h']:
            self.show_help()
        elif cmd in ['list', 'ls']:
            self.list_plugins()
        elif cmd in ['exit', 'quit', 'q']:
            self.running = False
            print("再见！")
        elif cmd == 'clear':
            os.system('cls' if os.name == 'nt' else 'clear')
        elif cmd == 'config':
            self.show_config_menu()
        else:
            # 尝试执行插件命令
            if self.plugin_manager.execute_plugin(cmd, args):
                pass  # 插件已处理
            else:
                print(f"未知命令: {cmd}")
                print("输入 'help' 查看可用命令")
                
    def show_help(self):
        """显示帮助信息"""
        print("\n=== 内置命令 ===")
        print("help, h      - 显示此帮助信息")
        print("list, ls     - 列出所有可用的功能模块")
        print("clear        - 清屏")
        print("config       - 配置管理")
        print("exit, quit, q - 退出程序")
        
        # 显示插件命令
        plugins = self.plugin_manager.get_loaded_plugins()
        if plugins:
            print("\n=== 功能模块命令 ===")
            for name, plugin in plugins.items():
                description = getattr(plugin, 'description', '无描述')
                print(f"{name:<12} - {description}")
                
    def list_plugins(self):
        """列出已加载的插件"""
        plugins = self.plugin_manager.get_loaded_plugins()
        
        if not plugins:
            print("暂无已加载的功能模块")
            return
            
        print(f"\n已加载 {len(plugins)} 个功能模块:")
        print("-" * 50)
        
        for name, plugin in plugins.items():
            status = "✓ 已启用" if getattr(plugin, 'enabled', True) else "✗ 已禁用"
            version = getattr(plugin, 'version', '1.0.0')
            description = getattr(plugin, 'description', '无描述')
            
            print(f"名称: {name}")
            print(f"版本: {version}")
            print(f"状态: {status}")
            print(f"描述: {description}")
            print("-" * 50)
            
    def show_config_menu(self):
        """显示配置菜单"""
        print("\n=== 配置管理 ===")
        print("1. 查看当前配置")
        print("2. 修改配置")
        print("3. 重置配置")
        print("4. 返回主菜单")
        
        choice = input("请选择操作 (1-4): ").strip()
        
        if choice == '1':
            self.show_current_config()
        elif choice == '2':
            self.modify_config()
        elif choice == '3':
            self.reset_config()
        elif choice == '4':
            return
        else:
            print("无效选择")
            
    def show_current_config(self):
        """显示当前配置"""
        config = self.config_manager.get_all_config()
        print("\n当前配置:")
        for key, value in config.items():
            print(f"{key}: {value}")
            
    def modify_config(self):
        """修改配置"""
        print("配置修改功能待实现...")
        
    def reset_config(self):
        """重置配置"""
        confirm = input("确定要重置所有配置吗？(y/N): ").strip().lower()
        if confirm == 'y':
            self.config_manager.reset_config()
            print("配置已重置")